<template>
  <el-dialog :title="title" :model-value="open" width="500px" append-to-body @update:model-value="updateOpen">
    <el-form ref="customerRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="客户名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入客户名称" />
      </el-form-item>
      <el-form-item label="所在城市" prop="city">
        <el-input v-model="form.city" placeholder="请输入所在城市" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="负责人" prop="personInCharge">
        <el-input v-model="form.personInCharge" placeholder="请输入负责人" />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系方式" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getCurrentInstance, reactive, ref, toRefs, watch } from 'vue';

// 获取当前组件的实例对象
const proxy = getCurrentInstance();

// 接受父组件的事件
const emit = defineEmits(['cancelBox', 'submitForm']);

const props = defineProps({
  title: {
    type: String,
    default: '新增客户'
  },
  open: {
    type: Boolean,
    required: true
  },
  formInfo: {
    type: Object,
    default: () => ({})
  }
});

// 定义表单参数
const form = reactive({
  id: null,
  name: null,
  city: null,
  email: null,
  address: null,
  personInCharge: null,
  phone: null,
  status: null,
  isDelete: null,
  createTime: null,
  updateTime: null,
  createBy: null,
  updateBy: null
});

// 抽离父组件传入的参数，解析成要的属性
const { title, open, formInfo } = toRefs(props);

// 监听器
watch(formInfo, (newValue) => {
  Object.assign(form, newValue);
}, { deep: true });

// 定义函数-提交表单
const submit = () => {
  proxy.refs.customerRef.validate((valid: boolean) => {
    if (valid) {
      emit('submitForm', form);
    }
  });
};

// 定义函数-取消表单
const cancel = () => {
  emit('cancelBox');
  resetForm();
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    name: null,
    city: null,
    email: null,
    address: null,
    personInCharge: null,
    phone: null,
    status: null,
    isDelete: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  });
};

const updateOpen = (value: boolean) => {
  emit('update:open', value);
};

const rules = reactive({
  id: [
    { required: true, message: "主键ID不能为空", trigger: "blur" }
  ],
  name: [
    { required: true, message: "客户名称不能为空", trigger: "blur" }
  ]
});
</script>

<style scoped></style>